package com.lzx.iteam;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.*;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.*;
import com.lzx.iteam.adapter.CRMContactAdapter;
import com.lzx.iteam.adapter.CRMDetailAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.net.*;
import com.lzx.iteam.widget.schedulecalendar.ScrollableLayout;
import com.lzx.iteam.widget.schedulecalendar.ViewHelper;
import com.lzx.iteam.selectimage.Bimp;
import com.lzx.iteam.selectimage.Res;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.lzx.iteam.widget.kpswitch.util.KPSwitchConflictUtil;
import com.lzx.iteam.widget.kpswitch.util.KeyboardUtil;
import com.lzx.iteam.widget.kpswitch.widget.KPSwitchPanelLinearLayout;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.lzx.iteam.EventDetailContentActivity.GET_QN_TOKEN;
import static com.lzx.iteam.widget.kpswitch.util.KPSwitchConflictUtil.mFlag;

/**
 * Created by Megan on 16/7/28.
 * 公海,销售线索
 */
public class CRMContactActivity extends MyBaseActivity implements View.OnClickListener, View.OnTouchListener {

    @FindViewById(id = R.id.top_title)
    private View mTitleLayout;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_iv_right)
    private ImageView mIvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.crm_detail_tv_name)
    private TextView mTvName;
    @FindViewById(id = R.id.title_v_line)
    private View mTitleLine;
    @FindViewById(id = R.id.lv_crm_follow)
    private ListView mFollowList;
    @FindViewById(id = R.id.lv_crm_detail)
    private ListView mDetailList;
    @FindViewById(id = R.id.crm_iv_voice_send)
    private ImageView mIvVoice;
    @FindViewById(id = R.id.crm_iv_image_send)
    private ImageView mIvImage;
    @FindViewById(id = R.id.crm_edit_input)
    private EditText mEditInput;
    @FindViewById(id = R.id.crm_iv_send)
    private ImageView mIvSend;
    @FindViewById(id = R.id.crm_iv_phone)
    private ImageView mIvPhone;
    @FindViewById(id = R.id.crm_iv_email)
    private ImageView mIvEmail;
    @FindViewById(id = R.id.crm_iv_loction)
    private ImageView mIvLoction;
    @FindViewById(id = R.id.tv_chat_image)
    private TextView mTvImage;
    @FindViewById(id = R.id.tv_chat_camera)
    private TextView mTvCamera;
    @FindViewById(id = R.id.chat_ll_sound)
    private LinearLayout mSoundLayout;
    @FindViewById(id = R.id.rl_chat_more)
    private LinearLayout mImageLayout;
    @FindViewById(id = R.id.crm_panel_root)
    private KPSwitchPanelLinearLayout mCRMPanelRoot;
    @FindViewById(id = R.id.crm_tv_follow)
    private TextView mTvFollow;
    @FindViewById(id = R.id.crm_tv_detail)
    private TextView mTvDetail;

    @FindViewById(id = R.id.chat_record)
    private ImageView mIvRecord;
    @FindViewById(id = R.id.chat_tv_sound_length)
    private TextView mTvSoundLength;
    @FindViewById(id = R.id.chat_tv_sound_send)
    private TextView mTvSoundSend;
    @FindViewById(id = R.id.chat_sound_record)
    private TextView mTvSoundRecord;
    @FindViewById(id = R.id.chat_tv_sound_notice)
    private TextView mTvSoundNotice;
    @FindViewById(id = R.id.crm_iv_send)
    private TextView mTvSend;
    @FindViewById(id = R.id.crm_scrollablelayout)
    private ScrollableLayout mScrollLayout;
    @FindViewById(id = R.id.crm_top_layout)
    private LinearLayout mTopLayout;
    @FindViewById(id = R.id.crm_contact_input_layout)
    private LinearLayout mInputLayout;
    @FindViewById(id = R.id.crm_contact_edit_layout)
    private LinearLayout mEditLayout;
    @FindViewById(id = R.id.chat_tv_sound_length_layout)
    private LinearLayout mLlSoundLengthLayout;
    @FindViewById(id = R.id.ll_small_image_layout)
    private LinearLayout mLayoutImage;
    @FindViewById(id = R.id.crm_layout_none)
    private LinearLayout mLayoutNull;
    @FindViewById(id = R.id.crm_public_layout)
    private View mPublicLayout;
    @FindViewById(id = R.id.crm_chance_layout)
    private View mChanceLayout;
    @FindViewById(id = R.id.crm_tv_client)
    private TextView mTvClientName;


    @FindViewById(id = R.id.tv_chance_market_stage_content)
    private TextView mTvMarketStage;
    @FindViewById(id = R.id.tv_chance_market_amount_content)
    private TextView mTvMarketAmount;
    @FindViewById(id = R.id.tv_chance_statement_date_content)
    private TextView mTvStatementDate;



    private int mType;  // 标志
    private String mFilePath;       // 照相图片文件地址
    private boolean mIsKeyboardShow;// 软键盘是否显示

    // 图片相关
    private Bitmap mBitMap;
    private List<Map<String, byte[]>> keyByte ;
    private JSONArray imageArray;
    private JSONArray voiceArray;
    private int mImageCount;    // 图片数量
    private int mStage = -1;    // 销售阶段

    // 语音相关
    private MediaPlayUtil mMediaPlayUtil;
    private ScaleAnimation mScaleBigAnimation;
    private ScaleAnimation mScaleLittleAnimation;
    private String mSoundData = "";     //语音数据
    private boolean isStop;             // 录音是否结束的标志
    private boolean isCanceled = false; // 是否取消录音
    private String dataPath;            // 录音文件地址
    private float downY;                // 录音手指触摸位置
    private MediaRecorder mRecorder;
    private long mStartTime;       // 录音开始时间
    private long mEndTime;         // 录音结束时间
    private int mTime;             // 录音时长
    private String mVoiceData;     // 录音数据

    private String mPhone,mEmail;
    private String mAddress;
    private String mLatitude,mLongitude;
    private String mGroupId;
    private String mCRMId;   // 线索ID  机会ID
    private String mComment; // 评论内容
    private AddressData mAddressBean;         // 地址bean

    private CRMContactAdapter mFollowAdapter;  // 跟进进度adapter
    private CRMDetailAdapter mDetailAdapter;   // 详细信息adapter
    private ArrayList<CRMDetailBean> mDetailAllData = new ArrayList<CRMDetailBean>();
    private ArrayList<CRMDetailBean> mDetailData = new ArrayList<CRMDetailBean>();
    private ArrayList<CRMCommentData> mCommentData = new ArrayList<CRMCommentData>();
    private PopupWindow mActionPop;
    private CRMBaseBean mCrmDetailData;       // 公海bean
    private CRMChanceBean mCrmChanceBean;     // 机会bean
    private Dialog mWaitDialog;

    private static final int CRM_BASE_DETAIL = 10002;      //  公海详情
    private static final int CRM_BASE_EDIT = 10003;        // 公海编辑
    private static final int CRM_BASE_COMMENT = 10004;     // 评论
    private static final int CRM_CHANCE_DETAIL = 10005;    //  机会详情
    private static final int CRM_CHANCE_EDIT = 10006;      // 机会编辑
    private static final int CRM_CHANCE_UPDATE = 10007;    // 机会更新
    private static final int CRM_CHANCE_UPDATE_STAGE = 10008;    // 机会更新销售阶段
    private static final int CRM_CHANCE_ADD_CONTACT = 10009;     // 新建联系人





    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CRM_CHANCE_DETAIL:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        Map<String, Object> map = null;
                        map= (Map<String, Object>) msg.obj;
                        mCrmChanceBean = (CRMChanceBean) map.get("info");
                        setChanceData();
                        mTvName.setText(mCrmChanceBean.getChance_name());
                        mStage = mCrmChanceBean.getMarket_stage();
                        mTvMarketStage.setText(CRMTextSelectActivity.stage[mStage] + CRMTextSelectActivity.stage_num[mStage] + " >");
                        mTvMarketAmount.setText("预计金额:"+mCrmChanceBean.getMarket_amount() + "元");
                        mTvStatementDate.setText("结单日期:"+DateUtil.formatDate(Long.parseLong(mCrmChanceBean.getStatement_date()) * 1000));
                        if (mStage == 5){ // 赢单
                            mIvRight.setVisibility(View.GONE);
                        }

                        mCommentData = (ArrayList<CRMCommentData>) map.get("history");
                        mFollowAdapter.bindData(mCommentData);
                        if (mDetailList.getVisibility() == View.GONE){
                            if (mCommentData.size() > 0){
                                mFollowList.setVisibility(View.VISIBLE);
                                mLayoutNull.setVisibility(View.GONE);
                            }else{
                                mFollowList.setVisibility(View.GONE);
                                mLayoutNull.setVisibility(View.VISIBLE);
                            }
                        }

                    }else{
                        Toast.makeText(CRMContactActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CRM_CHANCE_UPDATE_STAGE:
                    if (msg.arg1 == 0){
                        mCrmChanceBean.setMarket_stage(mStage);
                        if (mStage == 5){ // 赢单
                            mIvRight.setVisibility(View.GONE);
                        }
                        mTvMarketStage.setText(CRMTextSelectActivity.stage[mStage] + CRMTextSelectActivity.stage_num[mStage] + " >");
                        ArrayList<CRMCommentData> chances = (ArrayList<CRMCommentData>) msg.obj;
                        if (chances != null && chances.size() > 0){
                            for (int i = 0; i < chances.size(); i++) {
                                mCommentData.add(0,chances.get(i));
                            }
                        }
                        mFollowAdapter.bindData(mCommentData);
                        if (mDetailList.getVisibility() == View.GONE){
                            if (mCommentData.size() > 0){
                                mFollowList.setVisibility(View.VISIBLE);
                                mLayoutNull.setVisibility(View.GONE);
                            }else{
                                mFollowList.setVisibility(View.GONE);
                                mLayoutNull.setVisibility(View.VISIBLE);
                            }
                        }

                        for (int i = 0; i < mDetailAllData.size(); i++) {
                            if (mDetailAllData.get(i).getType() == 7 || mDetailAllData.get(i).getType() == 13){
                                mDetailAllData.get(i).setIndex(mStage);
                            }
                            if (mDetailAllData.get(i).getType() == 12){
                                mDetailAllData.get(i).setContent(System.currentTimeMillis()/1000 + "");
                            }
                            clearNullData();
                        }

                    }else{
                        Toast.makeText(CRMContactActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CRM_BASE_DETAIL:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        Map<String, Object> map = null;
                        map= (Map<String, Object>) msg.obj;
                        mCrmDetailData = (CRMBaseBean) map.get("info");
                        setDetailData();
                        mTvName.setText(mCrmDetailData.getName());
                        mCommentData = (ArrayList<CRMCommentData>) map.get("history");
                        mFollowAdapter.bindData(mCommentData);
                        if (mCommentData.size() > 0){
                            mFollowList.setVisibility(View.VISIBLE);
                            mLayoutNull.setVisibility(View.GONE);
                        }else{
                            mFollowList.setVisibility(View.GONE);
                            mLayoutNull.setVisibility(View.VISIBLE);
                        }
                        setEmailAndLoction();
                    }else{
                        Toast.makeText(CRMContactActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CRM_BASE_COMMENT:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        mComment = "";
                        mEditInput.setText("");
                        if (voiceArray != null) {
                            voiceArray = null;
                        }
                        CRMCommentData backData = (CRMCommentData) msg.obj;
                        mCommentData.add(0,backData);
                        mFollowAdapter.bindData(mCommentData);
                        if (mCommentData.size() > 0){
                            mFollowList.setVisibility(View.VISIBLE);
                            mLayoutNull.setVisibility(View.GONE);
                        }

                        // 判断,如果回复里面还有 Attachments 内容
                        if (!StringUtil.isEmpty(backData.getAttachments())){
                            Constants.NEW_CRM_REPLY_TIME = backData.getcTime();
                            if (Bimp.mPictureData.size() > 0){
                                Bimp.mPictureData.clear();
                            }
                            for(String data:Bimp.tempSelectBitmap){
                                Bimp.mPictureData.add(data);
                            }
                            Bimp.tempSelectBitmap.clear();
                        }
                        setImageMsg();

                    }else{
                        Toast.makeText(CRMContactActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        String path = (String) map.get("path");
                        String fileName = (String) map.get("fileName");
                        String voice=(String) map.get("voice");
                        if (!StringUtil.isEmpty(path)) {
                            voiceArray = new JSONArray();
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("type", "2");
                                jsonObject.put("duration", voice.split("tuandui@lzx")[1]);
                                jsonObject.put("data", fileName);
                                voiceArray.put(jsonObject);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            setVoice((String) map.get(fileName), path, fileName);
                            comment();
                        } else {
                            for (int i = 0; i < keyByte.size(); i++) {
                                Map<String, byte[]> map1 = keyByte.get(i);
                                for (String key : map1.keySet()) {
                                    setPhoto((String) map.get(key), map1.get(key), key);
                                }

                            }

                        }
                    }else{
                        Toast.makeText(CRMContactActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    }
                    break;

            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.crm_contact_layout);
        Log.d("InstanceState", "-- onCreate  ==  ");

    }

    @Override
    protected void onResume() {
        super.onResume();
        setImageMsg();
    }

    /**
     * 显示选择图片
     */
    private void setImageMsg() {
        int imgSize = 0;
        if (Bimp.tempSelectBitmap != null) {
            imgSize = Bimp.tempSelectBitmap.size();
            if (imgSize > 0) {
                mLayoutImage.setVisibility(View.VISIBLE);
                mLayoutImage.removeAllViews();
                for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
                    final String image = Bimp.tempSelectBitmap.get(i);
                    final int position = i;
                    final View view = LayoutInflater.from(mActivity).inflate(R.layout.small_image_layout, mLayoutImage, false);
                    RelativeLayout mLayout = (RelativeLayout) view.findViewById(R.id.rl_small_image);
                    ImageView mIvDelete = (ImageView) view.findViewById(R.id.iv_small_image_delete);
                    ImageView mIvImage = (ImageView) view.findViewById(R.id.iv_small_image);
                    ImageLoader.getInstance().displayImage("file://" + image, mIvImage, ImageLoaderInterface.optionEventImage);

                    mLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            Bimp.tempSelectBitmap.remove(position);
                            Bimp.deletePhoto(image);
                            Bimp.tempSelectBitmap.remove(image);
                            mLayoutImage.removeView(view);
                            if (Bimp.tempSelectBitmap.size() <= 0) {
                                mLayoutImage.setVisibility(View.GONE);
                            } else {
                                mLayoutImage.setVisibility(View.VISIBLE);
                            }
                        }
                    });
/*
                    mIvImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(EventDetailContentActivity.this, ImagePagerActivity.class);
                            intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_LOCAL_ARRAY);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, Bimp.tempSelectBitmap);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                            startActivity(intent);
                        }
                    });
*/
                    mLayoutImage.addView(view);
                }

            } else {
                mLayoutImage.setVisibility(View.GONE);
            }

        }


    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mType = intent.getIntExtra("type",0);
        mTvRight.setVisibility(View.GONE);
        mIvRight.setVisibility(View.VISIBLE);
        mTitleLine.setVisibility(View.GONE);
        mFollowAdapter = new CRMContactAdapter(mActivity);
        mFollowList.setAdapter(mFollowAdapter);

        mCRMId = intent.getStringExtra("clue_id");
        mGroupId = intent.getStringExtra("group_id");
        if (mType == Constants.CRM_PUBLIC_CLUE || mType == Constants.CRM_PRIVATE_CLUE){
            mTvTitle.setText("销售线索");
            mPublicLayout.setVisibility(View.VISIBLE);
            mTvClientName.setVisibility(View.GONE);
        }else if (mType == Constants.CRM_CHANCE){
            mTvTitle.setText("销售机会");
            mChanceLayout.setVisibility(View.VISIBLE);
        }else if (mType == Constants.CRM_CLIENT){
            mTvTitle.setText("客户");
            mPublicLayout.setVisibility(View.VISIBLE);
            mTvClientName.setVisibility(View.VISIBLE);
        }
        if (!StringUtil.isEmpty(mCRMId)){
            getDetailData();
        }

        mDetailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mType == 2 && mDetailData.get(position).getType() == 10){
                    Intent turn = new Intent(mActivity,CRMSelectContactActivity.class);
                    turn.putExtra("type",mType);
                    turn.putExtra("flag",1);
                    turn.putExtra("group_id",mGroupId);
                    turn.putExtra("clues",mCrmChanceBean.getClues());
                    startActivity(turn);
                }
            }
        });

        KeyboardUtil.attach(this, mCRMPanelRoot,
              // Add keyboard showing state callback, do like this when you want to listen in the
              // keyboard's show/hide change.
              new KeyboardUtil.OnKeyboardShowingListener() {
                  @Override
                  public void onKeyboardShowing(boolean isShowing) {
                      Log.d("ChatActivity", String.format("Keyboard is %s", isShowing ? "showing" : "hiding"));
                      mIsKeyboardShow = isShowing;
                  }
              });

        KPSwitchConflictUtil.attach(mCRMPanelRoot, mIvVoice, mIvImage, null, mEditInput,
              new KPSwitchConflictUtil.SwitchClickListener() {
                  @Override
                  public void onClickSwitch(boolean switchToPanel, int flag) {
                      if (switchToPanel) {
                          mEditInput.clearFocus();
                          Log.d("switchToPanel", " true ==  " + flag);
                          if (flag == 1) {
                              mTvSoundNotice.setVisibility(View.VISIBLE);
                              mIvRecord.setVisibility(View.VISIBLE);
                              mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                              mTvSoundNotice.setText("按住说话");
                              mTvSoundLength.setText("0" + '"');

                              setIconShow(1);
                              mSoundLayout.setVisibility(View.VISIBLE);
                              mImageLayout.setVisibility(View.GONE);
                          } else if (flag == 2) {
                              setIconShow(2);
                              mSoundLayout.setVisibility(View.GONE);
                              mImageLayout.setVisibility(View.VISIBLE);
                          }
                      } else {
                          mEditInput.requestFocus();
                          setIconShow(0);
                          Log.d("switchToPanel", " false ==  " + flag);
                      }
                  }
              });

        mScrollLayout.setVisibleHeight(50f);
        mScrollLayout.setOnScrollListener(new ScrollableLayout.OnScrollListener() {
            @Override
            public void onScroll(int currentY, int maxY) {

                ViewHelper.setTranslationY(mTopLayout, currentY * 0);
            }
        });
        setFollowAnfDetail(1);
        initSoundData();
        Res.init(this);
    }

    /**
     *  设置公海详情
     */
    private void setDetailData() {
        mDetailAllData.clear();
        mDetailAllData.add(new CRMDetailBean(1, "基本信息"));
        mDetailAllData.add(new CRMDetailBean(2, "跟进状态", mCrmDetailData.getStatus()));
        mDetailAllData.add(new CRMDetailBean("姓名", mCrmDetailData.getName()));
        mDetailAllData.add(new CRMDetailBean(3, "性别", mCrmDetailData.getSex()));
        mDetailAllData.add(new CRMDetailBean("公司", mCrmDetailData.getCompany()));
        mDetailAllData.add(new CRMDetailBean("部门", mCrmDetailData.getDepartment()));
        mDetailAllData.add(new CRMDetailBean("职务", mCrmDetailData.getJob()));

        mDetailAllData.add(new CRMDetailBean(1, "联系信息"));
        mDetailAllData.add(new CRMDetailBean("电话", mCrmDetailData.getTelephone()));
        mDetailAllData.add(new CRMDetailBean("手机", mCrmDetailData.getPhone()));
        mDetailAllData.add(new CRMDetailBean("邮箱", mCrmDetailData.getEmail()));
        mDetailAllData.add(new CRMDetailBean(4, "地址", mCrmDetailData.getAddress()));
        mDetailAllData.add(new CRMDetailBean("邮编", mCrmDetailData.getCode()));

        mDetailAllData.add(new CRMDetailBean(1, "其他信息"));
        mDetailAllData.add(new CRMDetailBean(5, "线索来源", mCrmDetailData.getOrigin()));
        mDetailAllData.add(new CRMDetailBean(6, "备注", mCrmDetailData.getRemark()));
//        mDetailAllData.add(new CRMDetailBean("最新活动记录时间", "2016-7-33"));
        clearNullData();

    }

    /**
     * 去除空的数据
     */
    private void clearNullData(){
        mDetailData.clear();
        for (int i = 0; i < mDetailAllData.size(); i++) {
            CRMDetailBean bean = mDetailAllData.get(i);
            if (bean.getType() != 1 && StringUtil.isEmpty(bean.getContent())) {
                if (bean.getIndex() == 0){
                    if (bean.getType() == 2 || bean.getType() == 5 || bean.getType() == 9){
                        mDetailData.add(bean);
                    }
                }else if (bean.getIndex() > 0){
                    mDetailData.add(bean);
                }
            } else {
                mDetailData.add(bean);
            }
        }

        if (mDetailAdapter == null) {
            mDetailAdapter = new CRMDetailAdapter(mActivity, mDetailData);
            mDetailList.setAdapter(mDetailAdapter);
        }else{
            mDetailAdapter.bindData(mDetailData);
        }

    }

    /**
     * 机会详情
     */
    private void setChanceData(){
        mDetailAllData.clear();
        mDetailAllData.add(new CRMDetailBean(1, "基本信息"));
        mDetailAllData.add(new CRMDetailBean("机会所有人", mCrmChanceBean.getOwner_name(),mCrmChanceBean.getOwner_img()));
        mDetailAllData.add(new CRMDetailBean("机会名称", mCrmChanceBean.getChance_name()));

        if (mCrmChanceBean.getClues().size() > 0){
            CRMLibraryListData base = mCrmChanceBean.getClues().get(0);
            mDetailAllData.add(new CRMDetailBean(10, "联系人", base.getName(),mCrmChanceBean.getClues().size()));
        }
        mDetailAllData.add(new CRMDetailBean(9,"机会类型", mCrmChanceBean.getChance_type()));
        mDetailAllData.add(new CRMDetailBean("销售金额", mCrmChanceBean.getMarket_amount()));
        mDetailAllData.add(new CRMDetailBean(7,"销售阶段", mCrmChanceBean.getMarket_stage()));
        mDetailAllData.add(new CRMDetailBean(13,"赢率", mCrmChanceBean.getMarket_stage()));
        mDetailAllData.add(new CRMDetailBean(12,"阶段更新时间", mCrmChanceBean.getUpdate_time()));
        mDetailAllData.add(new CRMDetailBean(8,"结单日期", mCrmChanceBean.getStatement_date()));
        mDetailAllData.add(new CRMDetailBean(11,"机会来源", mCrmChanceBean.getChance_source()));

        mDetailAllData.add(new CRMDetailBean(1, "其他信息"));
        mDetailAllData.add(new CRMDetailBean(8,"最新活动记录时间", mCrmChanceBean.getActive_time()));
        mDetailAllData.add(new CRMDetailBean(6, "备注", mCrmChanceBean.getRemark()));
        clearNullData();
    }

    /**
     * 设置邮箱 地址 电话信息
     */
    private void setEmailAndLoction(){
        mAddress = mCrmDetailData.getAddress();
        mLatitude = mCrmDetailData.getLatitude();
        mLongitude = mCrmDetailData.getLongitude();
        if (!StringUtil.isEmpty(mLatitude) && !StringUtil.isEmpty(mLongitude)){
            mAddressBean = new AddressData();
            mAddressBean.setLatitude(Double.parseDouble(mLatitude));
            mAddressBean.setLongitude(Double.parseDouble(mLongitude));
        }
        mPhone = mCrmDetailData.getPhone();
        mEmail = mCrmDetailData.getEmail();
    }
    /**
     * 设置邮箱 地址 话信息
     */
    private void setEmailAndLoction(Bundle bundle){
        mAddress = bundle.getString("address");
        mLatitude = bundle.getString("latitude");
        mLongitude = bundle.getString("longitude");
        if (!StringUtil.isEmpty(mLatitude) && !StringUtil.isEmpty(mLongitude)){
            mAddressBean = new AddressData();
            mAddressBean.setLatitude(Double.parseDouble(mLatitude));
            mAddressBean.setLongitude(Double.parseDouble(mLongitude));
        }
        mEmail = bundle.getString("email");
    }


    private void getDetailData(){
        httpReqDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID,mGroupId));
        CRMDetailMsg msg = null;
        if (mType == Constants.CRM_PUBLIC_CLUE || mType == Constants.CRM_PRIVATE_CLUE){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID,mCRMId));
            msg = new CRMDetailMsg(Constants.CRM_PUBLIC_CLUE,mHandler.obtainMessage(CRM_BASE_DETAIL));
            msg.mApi = AsynHttpClient.API_CRM_BASE_DETAIL;
        }else if (mType == Constants.CRM_CHANCE){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_ID,mCRMId));
            msg = new CRMDetailMsg(Constants.CRM_CHANCE,mHandler.obtainMessage(CRM_CHANCE_DETAIL));
            msg.mApi = AsynHttpClient.API_CRM_CHANCE_DETAIL;
        }
        msg.mParams = nvps;
        AsynHttpClient.getInstance(mActivity).execCRMHttp(msg);

    }


    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mIvRight.setOnClickListener(this);
        mTvFollow.setOnClickListener(this);
        mTvDetail.setOnClickListener(this);
        mTvSend.setOnClickListener(this);
        mEditLayout.setOnClickListener(this);
        mIvPhone.setOnClickListener(this);
        mIvEmail.setOnClickListener(this);
        mIvLoction.setOnClickListener(this);
        mTvImage.setOnClickListener(this);
        mTvCamera.setOnClickListener(this);
        mEditInput.setOnTouchListener(this);
        mScrollLayout.setOnTouchListener(this);
        mIvRecord.setOnTouchListener(new VoiceTouch());
        mTvMarketStage.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.tv_chat_image) {
            Intent intent2 = new Intent(this, ImageFileActivity.class);
            intent2.putExtra("image_number", 3);
            startActivity(intent2);
        } else if (v.getId() == R.id.tv_chat_camera) {
            mFilePath = PhotoUtil.doTakePhotoEvent(this);
        } else if (v.getId() == R.id.crm_iv_send){
            mComment = mEditInput.getText().toString().trim();
            if (StringUtil.isEmpty(mComment) && Bimp.tempSelectBitmap.size() == 0){
                Toast.makeText(CRMContactActivity.this, "请填写内容或选择图片", Toast.LENGTH_SHORT).show();
            }else{
                imageArray = new JSONArray();
                keyByte= new ArrayList<Map<String, byte[]>>();
                if (Bimp.tempSelectBitmap.size() > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String image : Bimp.tempSelectBitmap) {
                        Map<String, byte[]> token = new HashMap<String, byte[]>();
                        String key = UUID.randomUUID().toString() + System.currentTimeMillis();
                        if (mBitMap != null) {
                            if (!mBitMap.isRecycled()) {
                                mBitMap.recycle();
                            }
                            mBitMap = null;
                        }
                        mBitMap = PhotoUtil.readBitmapFromPath(mActivity, image, true);
                        if (mBitMap != null && !mBitMap.isRecycled()) {
                            byte[] bytes = PhotoUtil.compressImage(mBitMap);
                            token.put(key, bytes);
                        }
                        stringBuilder.append(key + ",");
                        keyByte.add(token);
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", "1");
                            jsonObject.put("data", key);
                            imageArray.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    getQnToken(stringBuilder.substring(0, stringBuilder.length() - 1));
                }
                comment();
                //隐藏下面语音图片键盘等布局
                setIconShow(0);
                KPSwitchConflictUtil.hidePanelAndKeyboard(mCRMPanelRoot);
                httpReqDlgShow();

            }
        } else if (mCRMPanelRoot.getVisibility() == View.VISIBLE || mIsKeyboardShow) {
            KPSwitchConflictUtil.hidePanelAndKeyboard(mCRMPanelRoot);
            setIconShow(0);
        }else{
            switch (v.getId()) {
                case R.id.title_ll_back:
                    finish();
                    break;
                case R.id.title_iv_right:
                    if (mType == Constants.CRM_CHANCE && mStage == 5){
                        Toast.makeText(CRMContactActivity.this,"对不起,该机会已处于赢单状态,请到客户库进行操作",Toast.LENGTH_LONG).show();
                        return;
                    }
                    showActionPop();
                    break;
                case R.id.crm_tv_follow:
                    if (Bimp.tempSelectBitmap.size() > 0){
                        mLayoutImage.setVisibility(View.VISIBLE);
                    }else{
                        mLayoutImage.setVisibility(View.GONE);
                    }
                    setFollowAnfDetail(1);
                    break;
                case R.id.crm_tv_detail:
                    mLayoutImage.setVisibility(View.GONE);
                    setFollowAnfDetail(2);
                    break;
                case R.id.crm_contact_edit_layout:
                    Intent edit = new Intent(mActivity, CRMCreateEditActivity.class);
                    if (mType == Constants.CRM_PUBLIC_CLUE || mType == Constants.CRM_PRIVATE_CLUE){
                        edit.putExtra("action_type", 2);
                        edit.putExtra("type", mType);
                        edit.putExtra("group_id", mGroupId);
                        edit.putExtra("clue_id", mCRMId);
                        edit.putExtra("crm_data", mDetailAllData);
                        if (mAddressBean != null){
                            edit.putExtra("address", mAddressBean);
                        }
                        startActivityForResult(edit,CRM_BASE_EDIT);
                    }else if (mType == Constants.CRM_CHANCE){
                        edit.putExtra("action_type", 5);
                        edit.putExtra("type", mType);
                        edit.putExtra("group_id", mGroupId);
                        edit.putExtra("chance_id", mCRMId);
                        edit.putExtra("crm_data", mCrmChanceBean);
                        startActivityForResult(edit,CRM_CHANCE_EDIT);
                    }
                    break;
                case R.id.crm_iv_phone:
                    if (!StringUtil.isEmpty(mPhone)){
                        showCallDialog();
                    }
                    break;
                case R.id.crm_iv_email:
                    if (!StringUtil.isEmpty(mEmail)){
                        Uri uri = Uri.parse("mailto:"+mEmail);
                        Intent email = new Intent(Intent.ACTION_SENDTO, uri);
                        startActivity(Intent.createChooser(email, "请选择邮件类应用"));
                    }else{
                        Toast.makeText(CRMContactActivity.this, "邮箱信息为空", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.crm_iv_loction:
                    openMapApp();
                    break;
                case R.id.tv_chance_market_stage_content:
                    if(mCrmChanceBean!=null&&mCrmChanceBean.getMarket_stage()!=5){
                        Intent update = new Intent(mActivity,CRMTextSelectActivity.class);
                        update.putExtra("action_select", 16);
                        update.putExtra("index", mCrmChanceBean.getMarket_stage());
                        update.putExtra("group_id", mGroupId);
                        update.putExtra("chance_id", mCRMId);
                        update.putExtra("chance_name", mCrmChanceBean.getChance_name());
                        startActivityForResult(update,CRM_CHANCE_UPDATE);
                    }else{
                        Toast.makeText(CRMContactActivity.this,"对不起,该机会已处于赢单状态,无法进行此操作",Toast.LENGTH_LONG).show();
                    }

                    break;
            }
        }
    }

    /**
     * 修改销售阶段
     */
    private void updateDetail(){

        if (mStage != -1 && mStage != mCrmChanceBean.getMarket_stage()){
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                  .getInstance().mSid));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_ID, mCRMId));

            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_NAME, mCrmChanceBean.getChance_name()));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_AMOUNT, mCrmChanceBean.getMarket_amount() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_STAGE, mStage + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATEMENT_DATE, mCrmChanceBean.getStatement_date()));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_TYPE, mCrmChanceBean.getChance_type() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_SOURCE, mCrmChanceBean.getChance_source() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, mCrmChanceBean.getRemark()));

            CRMChanceUpdateMsg msg  = new CRMChanceUpdateMsg(mHandler.obtainMessage(CRM_CHANCE_UPDATE_STAGE));
            msg.mApi = AsynHttpClient.API_CRM_CHANCE_UPDATE;
            msg.mParams = nvps;
            AsynHttpClient.getInstance(this).execCRMHttp(msg);
        }

    }

    /**
     * 打开地图
     */
    private void openMapApp(){
        Uri mapUri = null;
        if (!StringUtil.isEmpty(mAddress)){
            try {
                if (StringUtil.isEmpty(mLatitude) || StringUtil.isEmpty(mLongitude)){
                    mapUri = Uri.parse(StringUtil.getAddressUrl(mAddress));
                }else{
                    mapUri = Uri.parse(StringUtil.getAddressDetailUrl(mLatitude + "",mLongitude+ "",mAddress));
                }
                Intent loction = new Intent(Intent.ACTION_VIEW, mapUri);
                startActivity(loction);
            } catch (ActivityNotFoundException e){
                // 没有安装地图软件
                Toast.makeText(CRMContactActivity.this, "ActivityNotFoundException", Toast.LENGTH_SHORT).show();
                if (StringUtil.isEmpty(mLatitude) || StringUtil.isEmpty(mLongitude)){
                    mapUri = Uri.parse(StringUtil.getHtmlAddressUrl(mAddress));
                }else{
                    mapUri = Uri.parse(StringUtil.getHtmlAddressDetailUrl(mLatitude+ "",mLongitude+ "",mAddress));
                }
                Intent loction = new Intent(Intent.ACTION_VIEW, mapUri);
                startActivity(loction);
            } catch (Exception e){
                Toast.makeText(CRMContactActivity.this, "异常", Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(CRMContactActivity.this, "地址为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 打电话、发短信
     */
    private void showCallDialog() {
        mDialogUtil.titleOneDialog(mPhone, "发短信", "打电话");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                CommonCodeUtil.launchSendMessage(mActivity, mPhone, null);
                lDialog.dismiss();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                CommonCodeUtil.launchCallByNumber(mActivity, mPhone);
                lDialog.dismiss();
            }
        });

    }


    /**
     * 设置跟进进度和详情切换
     *
     * @param flag
     */
    private void setFollowAnfDetail(int flag) {
        if (flag == 1) {
            if (mCommentData.size() > 0){
                mFollowList.setVisibility(View.VISIBLE);
                mLayoutNull.setVisibility(View.GONE);
            }else{
                mFollowList.setVisibility(View.GONE);
                mLayoutNull.setVisibility(View.VISIBLE);
            }
            mInputLayout.setVisibility(View.VISIBLE);
            mDetailList.setVisibility(View.GONE);
            mEditLayout.setVisibility(View.GONE);
            mScrollLayout.getHelper().setCurrentContainer(mFollowList);

            mTvFollow.setBackgroundDrawable(getResources().getDrawable(R.drawable.crm_follow_selected));
            mTvDetail.setBackgroundDrawable(getResources().getDrawable(R.drawable.crm_detail_normal));

        } else {
            mFollowList.setVisibility(View.GONE);
            mLayoutNull.setVisibility(View.GONE);
            mInputLayout.setVisibility(View.GONE);
            mDetailList.setVisibility(View.VISIBLE);
            mEditLayout.setVisibility(View.VISIBLE);
            mScrollLayout.getHelper().setCurrentContainer(mDetailList);

            mTvFollow.setBackgroundDrawable(getResources().getDrawable(R.drawable.crm_follow_normal));
            mTvDetail.setBackgroundDrawable(getResources().getDrawable(R.drawable.crm_detail_selected));

        }
    }


    /**
     * 设置图标
     *
     * @param flag
     */
    private void setIconShow(int flag) {
        if (flag == 1) {
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
            mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_image_icon));
        } else if (flag == 2) {
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_voice_icon));
            mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
        } else {
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_voice_icon));
            mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_image_icon));
        }
    }

    /**
     * 弹出右上角操作
     */
    private void showActionPop() {
        final View mainView = LayoutInflater.from(this).inflate(R.layout.attendance_count_pop_layout, null);
        LinearLayout myCount = (LinearLayout) mainView.findViewById(R.id.ll_attendance_count_my);
        LinearLayout create = (LinearLayout) mainView.findViewById(R.id.ll_attendance_count_all);
        LinearLayout rank = (LinearLayout) mainView.findViewById(R.id.ll_attendance_rank);
        rank.setVisibility(View.GONE);
        TextView mBtnOne = (TextView) mainView.findViewById(R.id.pop_tv_one);
        TextView mBtnTwo = (TextView) mainView.findViewById(R.id.pop_tv_two);

        if (mType == Constants.CRM_PUBLIC_CLUE || mType == Constants.CRM_PRIVATE_CLUE){
            mBtnOne.setText("转为销售机会");
        } else if (mType == Constants.CRM_CHANCE){
            mBtnOne.setText("转移给他人");
            create.setVisibility(View.VISIBLE);
            mBtnTwo.setText("新建联系人");
        }

        mBtnOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mType == Constants.CRM_PUBLIC_CLUE || mType == Constants.CRM_PRIVATE_CLUE){
                    Intent edit = new Intent(mActivity, CRMCreateEditActivity.class);
                    edit.putExtra("action_type", 3);
                    edit.putExtra("type",mType);
                    edit.putExtra("contact_name", mCrmDetailData.getName());
                    edit.putExtra("group_id", mGroupId);
                    edit.putExtra("clue_id", mCRMId);
                    startActivity(edit);
                } else if (mType == Constants.CRM_CHANCE){
                    Intent turn = new Intent(mActivity,CRMSelectContactActivity.class);
                    turn.putExtra("type",mType);
                    turn.putExtra("flag",2);
                    turn.putExtra("group_id", mGroupId);
                    turn.putExtra("chance_id", mCRMId);
                    startActivity(turn);
                }
                mActionPop.dismiss();
            }
        });

        mBtnTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent edit = new Intent(mActivity, CRMCreateEditActivity.class);
                edit.putExtra("action_type", 1);
                edit.putExtra("type",mType);
                edit.putExtra("group_id", mGroupId);
                edit.putExtra("chance_id", mCRMId);
                startActivityForResult(edit,CRM_CHANCE_ADD_CONTACT);
                mActionPop.dismiss();
            }
        });
        int popWidth = Constants.dip2px(this, 160);
        //int popHeight = Constants.dip2px(mActivity, 168);
        mActionPop = new PopupWindow(mainView,
              popWidth,
              WindowManager.LayoutParams.WRAP_CONTENT);
        mActionPop.setFocusable(true);
        mActionPop.setOutsideTouchable(true);
        int xOffSet = getWindowManager().getDefaultDisplay().getWidth() - popWidth - 15;
        int yOffSet = Constants.dip2px(this, 6);
        mActionPop.setBackgroundDrawable(new ColorDrawable(
              Color.TRANSPARENT));
        mActionPop.showAsDropDown(mTitleLayout, xOffSet, -yOffSet);
        AlphaAnimation aa = new AlphaAnimation(0.4f, 1.0f);
        aa.setDuration(250);
        ScaleAnimation sa = new ScaleAnimation(0.2f, 1.0f, 0.2f,
              1.0f, Animation.RELATIVE_TO_SELF, 0.91f,
              Animation.RELATIVE_TO_SELF, 0f);
        sa.setDuration(250);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
        mainView.startAnimation(set);
    }

    /**
     * 初始化语音和文件目录
     */
    public void initSoundData() {
        dataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Sounds/";
        File folder = new File(dataPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        mMediaPlayUtil = MediaPlayUtil.getInstance();
//        mRecorder = new MediaRecorder();
    }

    /**
     * 生成一个随机的文件名
     *
     * @return
     */
    public String getRandomFileName() {
        String rel = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        rel = formatter.format(curDate);
        rel = rel + new Random().nextInt(1000);
        return rel;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (view.getId()) {
            case R.id.crm_edit_input:
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    setIconShow(0);
                    mFlag = 0;
                }
                break;
            case R.id.crm_scrollablelayout:
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    setIconShow(0);
                    KPSwitchConflictUtil.hidePanelAndKeyboard(mCRMPanelRoot);
                }
                break;

        }
        return false;

    }

    /**
     * 录音的触摸监听
     */
    class VoiceTouch implements View.OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = motionEvent.getY();
                    mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record_pressed));
                    mTvSoundNotice.setText("向上滑动取消发送");
                    mSoundData = dataPath + getRandomFileName() + ".amr";

                    // 防止开权限后崩溃
                    if (mRecorder != null) {
                        Log.i("recoder", " !=  null");
                        //mRecorder.release();
                        mRecorder.reset();
                    } else {
                        mRecorder = new MediaRecorder();
                        Log.i("recoder", " == null ");
                    }
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                    mRecorder.setOutputFile(mSoundData);
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    try {
                        mRecorder.prepare();
                    } catch (IOException e) {
                        Log.i("recoder", "prepare() failed-Exception-" + e.toString());
                    }
                    try {
                        mRecorder.start();
                        mStartTime = System.currentTimeMillis();
                        mLlSoundLengthLayout.setVisibility(View.VISIBLE);
                        mTvSoundLength.setText("0" + '"');
                        // 开启定时器
                        mHandler.postDelayed(runnable, 1000);
                    } catch (Exception e) {
                        Log.i("recoder", "prepare() failed-Exception-" + e.toString());
                    }
                    initScaleAnim();
                    mScaleBigAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (mScaleLittleAnimation != null) {
                                mIvRecord.startAnimation(mScaleLittleAnimation);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mScaleLittleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (mScaleBigAnimation != null) {
                                mIvRecord.startAnimation(mScaleBigAnimation);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mIvRecord.startAnimation(mScaleBigAnimation);

                    break;
                case MotionEvent.ACTION_UP:
                    if (!isStop) {
                        mEndTime = System.currentTimeMillis();
                        mTime = (int) ((mEndTime - mStartTime) / 1000);
                        stopRecord();
                        //stopPlay();

                        mTvSoundLength.setText("0" + '"');
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                        mTvSoundNotice.setText("按住说话");

                        try {
                            mVoiceData = StringUtil.encodeBase64File(mSoundData);
                            mVoiceData = mVoiceData + "tuandui@lzx" + mTime;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (isCanceled) {
                            deleteSoundFileUnSend();
                        } else {
                            //发送语音获取token
                            if (mVoiceData != null) {
                                getQnToken(mSoundData, mVoiceData);
                            }
                            //隐藏下面语音图片键盘等布局
                            setIconShow(0);
                            KPSwitchConflictUtil.hidePanelAndKeyboard(mCRMPanelRoot);
                        }
                        // }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL: // 开权限录音取消
                    Log.i("record_test", "权限影响录音录音");
                    mHandler.removeCallbacks(runnable);
                    mLlSoundLengthLayout.setVisibility(View.GONE);
                    if (mRecorder != null) {
                        mRecorder.release();
                        mRecorder = null;
                        System.gc();
                    }
                    mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                    mIvRecord.clearAnimation();
                    mTvSoundNotice.setText("按住说话");
                    isCanceled = true;
                    mScaleBigAnimation = null;
                    mScaleLittleAnimation = null;

                    break;

                case MotionEvent.ACTION_MOVE: // 滑动手指
                    Log.i("record_test", " ACTION_MOVE  权限影响录音录音");
                    float moveY = motionEvent.getY();
                    if (downY - moveY > 100) {
                        isCanceled = true;
                        mTvSoundNotice.setText("松开手指可取消录音");
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                    }
                    if (downY - moveY < 20) {
                        isCanceled = false;
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record_pressed));
                        mTvSoundNotice.setText("向上滑动取消发送");
                    }
                    break;

            }
            return true;
        }
    }


    /**
     * 初始化录音动画
     */
    public void initScaleAnim() {

        // TODO 放大
        mScaleBigAnimation = new ScaleAnimation(1.0f, 1.3f, 1.0f, 1.3f,
              Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleBigAnimation.setDuration(700);

        // TODO 缩小
        mScaleLittleAnimation = new ScaleAnimation(1.3f, 1.0f, 1.3f, 1.0f,
              Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleLittleAnimation.setDuration(700);

    }


    /**
     * 录音完毕后，若不发送，则删除文件
     */
    public void deleteSoundFileUnSend() {
        mTime = 0;
        if (!"".equals(mSoundData)) {
            try {
                File file = new File(mSoundData);
                file.delete();
                mSoundData = "";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 结束录音
     */
    public void stopRecord() {
        mIvRecord.clearAnimation();
        mScaleBigAnimation = null;
        mScaleLittleAnimation = null;
        if (mTime < 1) {
            deleteSoundFileUnSend();
            isCanceled = true;
            Toast.makeText(mActivity, "录音时间太短，长按开始录音", Toast.LENGTH_SHORT).show();
        } else {
            // 不加  "" 空串 会出  Resources$NotFoundException 错误
            mTvSoundLength.setText(mTime + "" + '"');
            Log.i("record_test", "录音成功");

        }
        mRecorder.setOnErrorListener(null);
        try {
            mRecorder.stop();
            mRecorder.reset();
            mRecorder.release();
        } catch (Exception e) {
            Log.i("recoder", "stop() failed");
            isCanceled = true;
            mIvRecord.setVisibility(View.VISIBLE);
            mTvSoundLength.setText("");
            Toast.makeText(mActivity, "录音发生错误,请重新录音", Toast.LENGTH_LONG).show();
            Log.i("record_test", "录音发生错误");
        }
        mHandler.removeCallbacks(runnable);
        if (mRecorder != null) {
            mRecorder = null;
            System.gc();
        }

    }


    // 定时器
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                long endTime = System.currentTimeMillis();
                int time = (int) ((endTime - mStartTime) / 1000);
                //mRlSoundLengthLayout.setVisibility(View.VISIBLE);
                mTvSoundLength.setText(time + "" + '"');
                // 限制录音时间不长于两分钟
                if (time > 119) {
                    isStop = true;
                    mTime = time;
                    stopRecord();
                    Toast.makeText(mActivity, "时间过长", Toast.LENGTH_SHORT).show();
                } else {
                    mHandler.postDelayed(this, 1000);
                    isStop = false;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = mDialogUtil.waitDialog();
//            mProgressDialog.setCancelable(false);
            if (!mWaitDialog.isShowing()){
                mWaitDialog.show();
            }
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    /**
     *
     */
    public void comment() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID,mGroupId));
        if(mType==Constants.CRM_PUBLIC_CLUE){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID, mCRMId));
        }else if(mType==Constants.CRM_CHANCE){
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CHANCE_ID, mCRMId));
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTENT, mComment));
        if (voiceArray != null && voiceArray.length() > 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, voiceArray.toString()));
        } else if (imageArray != null && imageArray.length() > 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, imageArray.toString()));
        } else {
//            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, ""));
        }

        CRMCommentMsg message = new CRMCommentMsg(mHandler.obtainMessage(CRM_BASE_COMMENT));
        if(mType==Constants.CRM_PUBLIC_CLUE){
            message.mApi = AsynHttpClient.API_CRM_BASE_COMMENT;
        }else if(mType==Constants.CRM_CHANCE){
            message.mApi = AsynHttpClient.API_CRM_CHANCE_COMMENT;
        }
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(message);
    }

    /**
     * 语音获取token
     * @param path
     * @param voiceData
     */
    public void getQnToken(String path,String voiceData) {
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, fileName));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.setParams(path, fileName,voiceData);
        getQnTokenMsg.mApi = AsynHttpClient.API_CRM_BASE_GET_QN_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execCRMHttp(getQnTokenMsg);
    }


    /**
     * 图片获取token
     * @param keys
     */
    public void getQnToken(String keys) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, keys));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.mApi = AsynHttpClient.API_CRM_BASE_GET_QN_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execCRMHttp(getQnTokenMsg);
    }


    //设置图片
    public void setPhoto(String token, byte[] file, String fileName) {
        if (token != null)
            Log.d("七牛--token", token);
        if (fileName != null)
            Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
              new UpCompletionHandler() {
                  @Override
                  public void complete(String key, ResponseInfo info, JSONObject response) {
                      Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                      ++mImageCount;
                      if (imageArray.length() == mImageCount) {
                          mHandler.postDelayed(new Runnable() {
                              @Override
                              public void run() {
                                  Bimp.deleteAllPhotoAfterSend();
                                  Constants.NEW_CRM_REPLY_TIME = "";
                                  Log.d("event_new_reply","  reply_time  ==  clear");
                              }
                          }, 3000);

                      }
                  }
              }, null);
    }


    public void setVoice(String token, String path, String fileName) {
        if (token != null)
            Log.d("七牛--token", token);
        if (fileName != null)
            Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(path, fileName, token,
              new UpCompletionHandler() {
                  @Override
                  public void complete(String key, ResponseInfo info, JSONObject response) {
                      Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);

                  }
              }, null);
    }

    /**
     * 弹出复制的pop
     *
     * @param v
     * @param context
     */
    public void showCopyPop(final View v, final String context) {
        //解析菜单view
        final View layoutMenu = LayoutInflater.from(this).inflate(R.layout.event_copy_layout, null);
        final PopupWindow window = new PopupWindow(layoutMenu, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //让弹出框获取焦点（为了让菜单里面的按钮可以点击）
        window.setFocusable(true);
        //触摸弹出框外面位置，自动dismiss
        window.setBackgroundDrawable(new ColorDrawable());//这句很关键！
        window.setOutsideTouchable(true);
        //显示PopupWindow
        /** 这个很重要 ,获取弹窗的长宽度 */
        layoutMenu.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = layoutMenu.getMeasuredWidth();
        int popupHeight = layoutMenu.getMeasuredHeight();
        /** 获取父控件的位置 */
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        /** 显示位置 */
        if (location[1] - popupHeight > 100) {
            layoutMenu.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bottom_corner_bg));
            window.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1]
                  - popupHeight);
        } else {
            layoutMenu.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.top_corner_bg));
            //window.showAsDropDown(v,0,0,Gravity.NO_GRAVITY);
            window.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1]
                  + v.getHeight());
        }
        v.setBackgroundResource(R.color.event_content_copy);
        window.update();

        //设置menu里面按钮点击监听
        TextView button1 = (TextView) layoutMenu.findViewById(R.id.event_tv_copy);//复制
        layoutMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // clip.getText(); // 粘贴
                clip.setText(context); // 复制
                v.setBackgroundResource(R.color.white);
                Toast.makeText(mActivity, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
                window.dismiss();
            }
        });
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                v.setBackgroundResource(R.color.white);
            }
        });

    }

    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation
              == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
            //当前为横屏， 在此处添加额外的处理代码
            Log.d("InstanceState", "--onConfigurationChanged  ==  横屏 " );

        } else if (this.getResources().getConfiguration().orientation
              == android.content.res.Configuration.ORIENTATION_PORTRAIT) {
            //当前为竖屏， 在此处添加额外的处理代码
            Log.d("InstanceState", "--onConfigurationChanged  ==  竖屏 ");

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("pic_path", mFilePath);
        Log.d("InstanceState", "-- onSaveInstanceState  ==  ");
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        mFilePath = savedInstanceState.getString("pic_path");
        Log.d("InstanceState", "-- onRestoreInstanceState  ==  " + mFlag);
        KPSwitchConflictUtil.showPanel(mCRMPanelRoot);
        setIconShow(1);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PhotoUtil.CAMERA_WITH_DATAA:
                    if (Bimp.tempSelectBitmap.size() < 3 && resultCode == RESULT_OK) {
                        Bitmap bitmap = PhotoUtil.readBitmapFromPath(this, mFilePath, false);
                        int degree = PhotoUtil.getExifOrientation(mFilePath);
                        if (degree != 0) {
                            bitmap = PhotoUtil.rotaingImageView(bitmap, degree);
                            FileUtils.deleteFolderFile(mFilePath, true);
                            mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Images/" + PhotoUtil.saveBitmaptoSdCard(bitmap, "/Yun/Images");
                        }
                        Bimp.tempSelectBitmap.add(mFilePath);
                        setImageMsg();
                    }
                    break;
                case CRM_BASE_EDIT:
                    mDetailAllData.clear();
                    mDetailAllData = (ArrayList<CRMDetailBean>) data.getSerializableExtra("crm_data");
                    clearNullData();
                    setEmailAndLoction(data.getBundleExtra("detail"));
                    break;
                case CRM_CHANCE_EDIT:
                    /*mCrmChanceBean = (CRMChanceBean) data.getSerializableExtra("crm_data");
                    setChanceData();*/
                    getDetailData();
                    break;
                case CRM_CHANCE_UPDATE:
                    mStage = data.getIntExtra("index",-1);
                    if (mStage != -1){
                        updateDetail();
                    }
                    break;
                case CRM_CHANCE_ADD_CONTACT:
                    CRMLibraryListData clue = (CRMLibraryListData) data.getSerializableExtra("contact");
                    /**
                     * 更新进度
                     */
                    ArrayList<String> nameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
                    if (nameCard != null){
                        CRMCommentData comment = new CRMCommentData();
                        comment.setFlag(1);
                        comment.setContent(nameCard.get(0) + "添加新联系人:" + clue.getName());
                        comment.setcTime(System.currentTimeMillis()/1000 + "");
                        mCommentData.add(0,comment);
                        mFollowAdapter.bindData(mCommentData);
                    }
                    /**
                     * 更新详细信息
                     */
                    ArrayList<CRMLibraryListData> clues = mCrmChanceBean.getClues();
                    clues.add(clue);
                    mCrmChanceBean.setClues(clues);
                    for (int i = 0; i < mDetailAllData.size(); i++) {
                        CRMDetailBean bean = mDetailAllData.get(i);
                        if (bean.getType() == 10){
                            bean.setIndex(mCrmChanceBean.getClues().size());
                        }
                    }
                    clearNullData();
                    break;

            }
        }
    }

    @Override
    public void onBackPressed() {
        if (mCRMPanelRoot.getVisibility() == View.VISIBLE) {
            KPSwitchConflictUtil.hidePanelAndKeyboard(mCRMPanelRoot);
            setIconShow(0);
        } else {
            super.onBackPressed();
        }
        Bimp.deleteAllPhoto();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayUtil.isPlaying()) {
            mMediaPlayUtil.stop();
        }
    }
}
